/*
#include <stdio.h>
#include <math.h>
*/

#define NANOSEC 1000000000
#define MICROSEC 1000000
#define MILLISEC 1000
#define FOSC 40000000
#define TPNS (4*(NANOSEC / FOSC))

#define STEPS360 400

unsigned short ta;
unsigned int treg;
unsigned int treginitial;
unsigned int tregfinal;
unsigned short vinitial, vfinal;
signed int totalreg;
signed int constreg;
unsigned int step;
unsigned char phase;
/*
unsigned short compute_timer(unsigned short v) {
  unsigned int tc = (360 * MICROSEC) / STEPS360;
  return (unsigned short)((tc * 1000) / (v * TPNS));
}
*/
unsigned int compute_timer(unsigned int v) {
  unsigned int tc = (360 * MICROSEC) / STEPS360;
  return (unsigned int)((tc * 1000) / (v * TPNS));
}

int main(void) {
  vfinal = 1;
  //  treginitial = 65535;
  treginitial=compute_timer(1440);
  ta = 2000; /* MICROSEC */
  tregfinal = compute_timer(vfinal);
  vinitial = compute_timer(treginitial);
  phase = 1;
  totalreg = ((int)vinitial*(MICROSEC / TPNS))/ ((signed int)(vfinal - vinitial));
  totalreg = totalreg * ta;
  constreg=(((NANOSEC / TPNS)) / (STEPS360));
  constreg = 360*constreg;
  constreg= constreg / ((signed int)(vfinal -vinitial) * TPNS); 
  printf("%u %u %u %d %d\n", tregfinal, vinitial, treginitial, totalreg, constreg);
  treg = treginitial;
  step = 0;
  while(1) {
    unsigned int temp;
    step += 1;
    totalreg += treg;
    temp = (ta * MICROSEC) / totalreg;
    treg=(unsigned int) (constreg * temp);
    printf("%d %u %d\n", step, treg, totalreg);
    if ((phase == 0) && (treg <= tregfinal)) break;
    if ((phase == 1) && (treg >= tregfinal)) break;
  }
}
